package com.stylefeng.guns.modular.flagglory.controller;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.stylefeng.guns.common.persistence.model.Department;
import com.stylefeng.guns.core.base.controller.BaseController;
import com.stylefeng.guns.core.log.LogObjectHolder;
import com.stylefeng.guns.modular.flagglory.service.IDepartmentService;
import com.stylefeng.guns.modular.flagglory.warpper.DepartmentWarpper;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.validation.Valid;
import java.util.List;
import java.util.Map;

/**
 * 部门控制器
 *
 * @author fengshuonan
 * @Date 2018-01-31 14:14:14
 */
@Controller
@RequestMapping("/department")
public class DepartmentController extends BaseController {

    private String PREFIX = "/flagGlory/department/";

    @Autowired
    private IDepartmentService departmentService;

    /**
     * 跳转到部门首页
     */
    @RequestMapping("")
    public String index() {
        return PREFIX + "department.html";
    }

    /**
     * 跳转到添加部门
     */
    @RequestMapping("/department_add")
    public String departmentAdd() {
        return PREFIX + "department_add.html";
    }

    /**
     * 跳转到修改部门
     */
    @RequestMapping("/department_update/{departmentId}")
    public String departmentUpdate(@PathVariable Integer departmentId, Model model) {
        Department department = departmentService.selectById(departmentId);
        model.addAttribute("item", department);
        Integer pid = department.getPid();
        Department pDepartment = departmentService.selectById(pid);
        if (null != pDepartment) {
            model.addAttribute("pName", pDepartment.getFullname());
        }else{
            model.addAttribute("pName","无");
        }
        LogObjectHolder.me().set(department);
        return PREFIX + "department_edit.html";
    }

    /**
     * 获取部门列表
     */
    @RequestMapping(value = "/list")
    @ResponseBody
    public Object list(String condition) {
        EntityWrapper<Department> departmentEntityWrapper = new EntityWrapper<>();
        departmentEntityWrapper.orderBy("sort");
        List<Map<String, Object>> departments = departmentService.selectMaps(departmentEntityWrapper);
        return super.warpObject(new DepartmentWarpper(departments));
    }

    /**
     * 新增部门
     */
    @RequestMapping(value = "/add")
    @ResponseBody
    public Object add(@Valid Department department, BindingResult result) throws Exception {
        if (result.hasErrors()) {
            throw new Exception(result.getFieldError().getDefaultMessage());
        }
        Integer pid = department.getPid();
        Department pDepartment = departmentService.selectById(pid);
        if (null != pDepartment) {
            String pPids = pDepartment.getPids();
            if (StringUtils.isNotBlank(pPids)) {
                department.setPids(pPids + "_" + pDepartment.getId());
            } else {
                department.setPids(pDepartment.getId().toString());
            }
        } else {
            department.setPids("");
        }
        departmentService.insert(department);
        return super.SUCCESS_TIP;
    }

    /**
     * 删除部门
     */
    @RequestMapping(value = "/delete")
    @ResponseBody
    public Object delete(@RequestParam Integer departmentId) {

        departmentService.deleteById(departmentId);
        return SUCCESS_TIP;
    }

    /**
     * 修改部门
     */
    @RequestMapping(value = "/update")
    @ResponseBody
    public Object update(@Valid Department department, BindingResult result) throws Exception {
        if (result.hasErrors()) {
            throw new Exception(result.getFieldError().getDefaultMessage());
        }
        Integer pid = department.getPid();
        if (department.getId() == pid) {
            throw new Exception("不能选择当前部门为父部门！");
        }
        Department pDepartment = departmentService.selectById(pid);
        if (null != pDepartment) {
            String pPids = pDepartment.getPids();
            if (StringUtils.isNotBlank(pPids)) {
                department.setPids(pPids + "_" + pDepartment.getId());
                String[] pPidArray = pPids.split("_");
                for (String id : pPidArray) {
                    if (id.equals(department.getId().toString())) {
                        throw new Exception("当前选择父部门为当前部门的子部门之一，请更换！");
                    }
                }
            } else {
                department.setPids(pDepartment.getId().toString());
            }
        } else {
            department.setPids("");
        }
        departmentService.updateById(department);
        return super.SUCCESS_TIP;
    }

    /**
     * 部门详情
     */
    @RequestMapping(value = "/detail/{departmentId}")
    @ResponseBody
    public Object detail(@PathVariable("departmentId") Integer departmentId) {
        return departmentService.selectById(departmentId);
    }

    @RequestMapping(value = "/tree")
    @ResponseBody
    public Object tree() {
        return departmentService.tree();
    }
}
